//
//  MarketViewController.m
//  digitalCurrency
//
//  Created by sunliang on 2018/1/26.
//  Copyright © 2018年 XinHuoKeJi. All rights reserved.
//


#import "MarketViewController.h"
#import "CTLoginVC.h"
#import "CTHeaderView.h"
#import "CTCoinListCell.h"
#import "HomeNetManager.h"
#import "JKBannarView.h"
#import "MineNetManager.h"
#import "VersionUpdateModel.h"
#import "CEMainGoldVC.h"
#import "CTAnnouncementVC.h"
#import "HFFanClubJoinRollView.h"
#import "CTCoinListModel.h"
#import "PlatformMessageModel.h"

#import "SDCycleScrollView.h"

#import "ShangChengVC.h"
#import "XinDaiVC.h"
#import "GengDuoVC.h"
#import "MyNodeVC.h"
#define Start_X 0.0f           // 第一个按钮的X坐标
#define Start_Y SafeAreaTopHeight-20           // 第一个按钮的Y坐标
#define Width_Space 0.0f        // 2个按钮之间的横间距
#define Height_Space 0.0f      // 竖间距
#define Button_Height 70.0f    // 高
#define Button_Width (kWindowW/5.0)     // 宽


@interface MarketViewController ()
<SDCycleScrollViewDelegate>
{
//    dispatch_source_t _timer;
}
    
@property (nonatomic, strong) NSMutableArray *coinList;
@property (nonatomic, strong) CTHeaderView *headerView;
@property (nonatomic, strong) UIView *sectionHeaderView;
@property (nonatomic, strong) UILabel *sectionFirstView;
@property (nonatomic, strong) UILabel *sectionSecondView;
@property (nonatomic, strong) UILabel *sectionThirdView;

@property (nonatomic, strong) VersionUpdateModel *versionModel;
@property (nonatomic, strong) NSMutableArray *bannerArr;
@property (nonatomic, strong) NSMutableArray *platformMessageArr;

@property (nonatomic, strong) SDCycleScrollView *cycleScrollView;
    
@end

@implementation MarketViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = tMainColor;
    
    self.coinList = [NSMutableArray array];
    self.bannerArr = [NSMutableArray array];
    
    [self.view addSubview:self.tableView];
    self.tableView.rowHeight = 70;
    self.tableView.separatorColor = [UIColor clearColor];
    [self.tableView registerClass:[CTCoinListCell class] forCellReuseIdentifier:@"headlistcell"];
    [self setTablewViewHeard];
//    [self headRefreshWithScrollerView:self.tableView];
    [self setTablewViewHeard];
    
    [self clickHandle];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    [self versionUpdate];
    
    self.title = LocalizationKey(@"Home page");;
    self.sectionFirstView.text  = LocalizationKey(@"Name");
    self.sectionSecondView.text = LocalizationKey(@"Latest price");
    self.sectionThirdView.text  = LocalizationKey(@"Price limit");
    
    [self updateUserInfo];
    
       if(![YLUserInfo isLogIn]) {
           [self showLoginViewController];
       }
       else {
           [self getBannerData];
           [self getNotice];
           [self startTimer];
       }
        
}

- (void)updateUserInfo {
    [MineNetManager getUserStarInfo:[YLUserInfo shareUserInfo].ID CompleteHandle:^(id resPonseObj, int code) {
        if (code) {
            NSInteger codeInt = [resPonseObj[@"code"] intValue];
            if (codeInt == 0) {
                [UserDefault setString:tUserName value:[NSString stringWithFormat:@"%@",resPonseObj[@"data"][@"userName"]]];
                [UserDefault setString:tValue value:[NSString stringWithFormat:@"%@",resPonseObj[@"data"][@"value"]]];
                [UserDefault setString:tNode value:[NSString stringWithFormat:@"%@",resPonseObj[@"data"][@"node"]]];
            }
            [self.tableView reloadData];
        }
    }];
}

- (void)clickHandle {
    @weakify(self);
    [[self.headerView.pointGold rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        CEMainGoldVC *vc = [[CEMainGoldVC alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }];
    
    __weak typeof(self)weakself = self;
    self.headerView.rollView.RollViewBlock = ^(NSInteger index) {
        CTAnnouncementVC *avc = [[CTAnnouncementVC alloc] init];
        avc.hidesBottomBarWhenPushed = YES;
        [weakself.navigationController pushViewController:avc animated:YES];
    };
    
}

//#pragma mark-下拉刷新数据
//- (void)refreshHeaderAction {
//    [self getMinerInfo];
//}

-(void)setTablewViewHeard {
    CGRect rect    = self.view.bounds;
    rect.origin.y = 0;
    rect.size.height = kWindowH;
    self.tableView.frame = rect;
    [self.tableView registerClass:[CTCoinListCell class] forCellReuseIdentifier:@"coinlistcell"];
    
    self.headerView = [[CTHeaderView alloc]initWithFrame:CGRectMake(0, 0, kWindowW, 184/375.0*kWindowW+70)];
    self.headerView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableHeaderView  = self.headerView;
    
    self.cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kWindowW, 184/375.0*kWindowW) shouldInfiniteLoop:YES imageNamesGroup:self.bannerArr];
    self.cycleScrollView.delegate = self;
    self.cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleNone;
    [self.headerView addSubview:self.cycleScrollView];
    self.cycleScrollView.scrollDirection = UICollectionViewScrollDirectionHorizontal;
}


- (void)getAllCoinInfo {
    [HomeNetManager getAllCoinInfo:[YLUserInfo shareUserInfo].ID CompleteHandle:^(id resPonseObj, int code) {
        
        if (code) {
            NSInteger codeInt = [resPonseObj[@"code"] integerValue];
            if (codeInt == 0) {
                NSArray *data = resPonseObj[@"data"][@"list"];
                if (data.count) {
                    [self.coinList removeAllObjects];
                }
                for (NSDictionary *sub in data) {
                    CTCoinListModel *model = [CTCoinListModel mj_objectWithKeyValues:sub];
                    [self.coinList addObject:model];
                }
                
                [self.tableView reloadData];
            }
            else {
                [self.view makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
            }
        }
        else {
            [self.view makeToast:LocalizationKey(@"noNetworkStatus") duration:1.5 position:CSToastPositionCenter];
        }
    }];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.coinList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CTCoinListCell *cell = [CTCoinListCell createTableView:tableView];
    
    CTCoinListModel *model = self.coinList[indexPath.row];
    
    [cell.coinImgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMAGE,model.coinUrl]] placeholderImage:[UIImage imageNamed:@"announce"]];

    cell.coinName.text      = model.coinSymbol;
    cell.coinChinaName.text = model.coinEnglishName;

   cell.coinRMBPrice.text = [NSString stringWithFormat:@"￥%@",[ToolUtil judgeStringForDecimalPlaces:model.coinPriceRmb point:2]];
    cell.coinDollarPrice.text = [NSString stringWithFormat:@"$%@",[ToolUtil judgeStringForDecimalPlaces:model.coinPriceUSDT point:4]];
    
    NSString *percent = model.coinFluctuation;
    NSString *color = [percent substringToIndex:1];
        
    if ([color isEqualToString:@"-"]) {
        [cell.coinPercent setTitleColor:[UIColor colorWithHEX:@"#FF0D21"] forState:UIControlStateNormal];
    }
    else {
        [cell.coinPercent setTitleColor:[UIColor colorWithHEX:@"#06C669"] forState:UIControlStateNormal];
    }
   
    [cell.coinPercent setTitle:percent forState:UIControlStateNormal];
    
    return cell;
}
    
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    return self.sectionHeaderView;
}
    
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 42;
}

-(void)dealloc {
    NSLog(@"%s",__func__);
}

- (void)startTimer {
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
          [self getAllCoinInfo];
      });
//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
//    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),10.0*NSEC_PER_SEC, 0); //每秒执行
//    dispatch_source_set_event_handler(_timer, ^{
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self getAllCoinInfo];
//        });
//    });
//    dispatch_resume(_timer);
}

- (UIView *)sectionHeaderView {
    if (!_sectionHeaderView) {
        _sectionHeaderView = [[UIView alloc] init];
        _sectionHeaderView.backgroundColor = [UIColor whiteColor];
        NSArray *titles = @[LocalizationKey(@"Name"),LocalizationKey(@"Latest price"),LocalizationKey(@"Price limit")];
        CGFloat width1_3 = (SCREEN_WIDTH)/3.0;
        for (int i = 0; i < 3; i++) {
            UILabel *label = [[UILabel alloc] init];
            [_sectionHeaderView addSubview:label];
            label.text = titles[i];
            label.textColor = tThreeColor;
            label.font = [UIFont systemFontOfSize:14];
            label.textAlignment = NSTextAlignmentCenter;
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(width1_3);
                make.left.mas_equalTo(width1_3*i);
                make.height.mas_equalTo(42);
            }];
            if (i == 0) {
                self.sectionFirstView = label;
            }
            else if (i == 1) {
                self.sectionSecondView = label;
            }
            else {
                self.sectionThirdView = label;
            }
        }
    }
    
    return _sectionHeaderView;
}
    
-(void)getBannerData {
    
    [HomeNetManager advertiseBannerCompleteHandle:^(id resPonseObj, int code) {
        //NSLog(@"首页轮播图 --- %@",resPonseObj);
        if (code) {
            if ([resPonseObj[@"code"] integerValue] == 0) {
                NSArray *banners = resPonseObj[@"data"];
                self.bannerArr = [NSMutableArray array];
                for (NSDictionary *dic in banners) {
                    [self.bannerArr addObject:dic[@"url"]];
                }
                
                self.cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kWindowW, 184/375.0*kWindowW) shouldInfiniteLoop:YES imageNamesGroup:self.bannerArr];
                self.cycleScrollView.delegate = self;
                self.cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleNone;
                [self.headerView addSubview:self.cycleScrollView];
                self.cycleScrollView.scrollDirection = UICollectionViewScrollDirectionHorizontal;
                [self.tableView reloadData];
            }
            else {
                [self.view makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
            }
        }
        else {
            [self.view makeToast:LocalizationKey(@"noNetworkStatus") duration:1.5 position:CSToastPositionCenter];
        }
    }];
}

#pragma mark-获取平台消息
-(void)getNotice {
    [HomeNetManager getPlatformMessageForCompleteHandleWithPageNo:@"1" withPageSize:@"20" CompleteHandle:^(id resPonseObj, int code) {
        [EasyShowLodingView hidenLoding];
        NSLog(@"获取平台消息 ---- %@", resPonseObj);
        if (code) {
            if ([resPonseObj[@"code"] integerValue] == 0) {
                //[self.platformMessageArr removeAllObjects];
                NSArray *arr = resPonseObj[@"data"][@"content"];
                NSMutableArray *muArr = [NSMutableArray arrayWithCapacity:0];
                NSMutableArray *muRightArr = [NSMutableArray arrayWithCapacity:0];

                for (NSDictionary *dic in arr) {
                    [muArr addObject:dic[@"title"]];
                    [muRightArr addObject:dic[@"createTime"]];

                }
                [self.headerView.rollView setNewArray:muArr rightArr:muRightArr];
               // [self.tableView reloadData];
            }else{
                [self.view makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
            }
        }else{
            [self.view makeToast:LocalizationKey(@"noNetworkStatus") duration:1.5 position:CSToastPositionCenter];
        }
    }];
}
    
- (BOOL)hasChinese:(NSString *)str {
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff)
        {
            return YES;
        }
    }
    return NO;
}
#pragma mark - 版本更新接口请求
-(void)versionUpdate {
    [MineNetManager versionUpdateForId:@"1" CompleteHandle:^(id resPonseObj, int code) {
        //NSLog(@"版本更新接口请求 --- %@",resPonseObj);
        if (code) {
            if ([resPonseObj[@"code"] integerValue] == 0) {
                self.versionModel = [VersionUpdateModel mj_objectWithKeyValues:resPonseObj[@"data"]];
                //_versionModel.version = @"1.0.2";
                // app当前版本
                NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
                NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
                NSLog(@"app_Version ---- %@",app_Version);
                if ([app_Version compare:_versionModel.version_code] == NSOrderedSame ||[app_Version compare:_versionModel.version_code] == NSOrderedDescending) {
                    //不需要更新
                    NSLog(@"%@",_versionModel.version_code);
                }
                else {
                    //版本更新
                    NSURL *url = [NSURL URLWithString:_versionModel.url];
                    
                    [LEEAlert alert].config
                    .LeeTitle(LocalizationKey(@"warmPrompt"))
                    .LeeAddContent(^(UILabel *label) {
                        label.text = LocalizationKey(@"当前有新的版本，请前往下载升级！");
                        label.font = [UIFont systemFontOfSize:16];
                    })
                    .LeeAddAction(^(LEEAction *action) {
                        action.title      = LocalizationKey(@"ok");
                        action.titleColor = kRGBColor(43, 43, 43);
                        action.font       = [UIFont systemFontOfSize:16];
                        action.clickBlock = ^{
                            if ([[UIApplication sharedApplication] respondsToSelector:@selector(openURL:options:completionHandler:)]) {
                                [[UIApplication sharedApplication]
                                 openURL:url
                                 options:@{}
                                 completionHandler:nil];
                            }
                        };
                    })
                    .LeeShow();
                }
            }
            else if ([resPonseObj[@"code"] integerValue]==4000||[resPonseObj[@"code"] integerValue]==3000){
            }
            else if ([resPonseObj[@"code"] integerValue] == 500) {
                //无版本更新，不提示
            }
            else {
                
            }
        }
        else {
            
        }
    }];
}
    
@end
